﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Smarly.Core;
using Smarly.Core.Database;

namespace Smarly.Ebook
{
	public class SectionModel : ModelStateObject
	{
		internal Int16 SectionId { get; set; }
		internal Int16 ParentSectionId { get; set; }
		internal int LeftKey { get; set; }
		internal byte Level { get; set; }
		public string HashTag { get; set; }
		public string Name { get; set; }
		public List<SectionModel> Children { get; set; }
		public SectionModel Parent { get; set; }


		public static List<SectionModel> Get()
		{
			List<SectionModel> flat;
			return Get(out flat);
		}

		public static List<SectionModel> Get(out List<SectionModel> flatList)
		{
			List<SectionModel> flat = flatList = new List<SectionModel>();

			return SqlRepository.ExecuteProcedureReader("Forum_Section_Get",
																					 new List<SpParam>
			                                     	{
			                                     		new SpParam {Name = "@fromLevel", Value = 1, Type = DbType.Int32},
			                                     		new SpParam {Name = "@tillLevel", Value = 2, Type = DbType.Int32},
			                                     	}, null,
																						(reader) =>
																						{
																							var result = new List<SectionModel>();

																							while (reader.Read())
																							{
																								flat.Add(new SectionModel
																								{
																									SectionId = reader.GetInt16("SectionId"),
																									ParentSectionId = reader.GetInt16("ParentSectionId"),
																									LeftKey = reader.GetInt32("LeftKey"),
																									Level = reader.GetByte("Level"),
																									HashTag = reader.GetString("HashTag"),
																									Name = reader.GetString("Name"),
																								});
																							}

																							result.AddRange(flat.Where(x => x.Level == 1).OrderBy(x => x.LeftKey));

																							CreateSectionTree(result, flat);

																							return result;
																						});

		}

		private static void CreateSectionTree(IEnumerable<SectionModel> roots, List<SectionModel> all)
		{
			foreach (var section in roots)
			{
				section.Children = all.Where(x => x.ParentSectionId == section.SectionId).OrderBy(x => x.LeftKey).ToList();

				foreach (var child in section.Children)
				{
					child.Parent = section;
				}

				if (section.Children != null && section.Children.Count > 0)
				{
					CreateSectionTree(section.Children, all);
				}
			}
		}
	}
}